package org.leiyang.gateway.Filters;

import io.netty.util.internal.StringUtil;
import org.leiyang.common.redis.ReactiveRedisCache;
import org.leiyang.common.util.Constants;
import org.leiyang.common.util.IpUtils;
import org.leiyang.common.util.ServletUtils;
import org.leiyang.gateway.config.IgnoreWhiteProperties;
import org.leiyang.gateway.service.RemoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Component
public class InnerFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(InnerFilter.class);

    @Autowired
    private IgnoreWhiteProperties ignoreWhite;
    @Autowired
    private ReactiveRedisCache redisCache;
    @Autowired
    private RemoteService remoteService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 白名单接口跳过不需要验证的路径
        if (ServletUtils.matches(url, ignoreWhite.getWhites()))
        {
            //仍然设置请求的源IP
            addHeader(mutate, Constants.CLIENT_IP, IpUtils.getClientIp(request));
            return chain.filter(exchange.mutate().request(mutate.build()).build());
//            return chain.filter(exchange);
        }
        String token = getToken(request);
        if (StringUtil.isNullOrEmpty(token))
        {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
//        LoginUser loginUser = TokenUtil.parseToken(token);
        log.info("本次请求头里的token: {}", token);
        return remoteService.parseToken(token).flatMap(lUser -> {
            if(Objects.isNull(lUser)) {
                return unauthorizedResponse(exchange, "非法令牌!");
            }
            return redisCache.keyExist(getTokenKey(token)).flatMap(exist -> {
                if(!exist) {
                    return unauthorizedResponse(exchange, "登录状态已过期");
                }
                // 设置用户信息到请求
                addHeader(mutate, Constants.USER_KEY, token);
                addHeader(mutate, Constants.DETAILS_USER_ID, lUser.getUserid());
                addHeader(mutate, Constants.DETAILS_USERNAME, lUser.getUsername());
                addHeader(mutate, Constants.CLIENT_IP, IpUtils.getClientIp(request));
                //设置客户端IP
//            addHeader(mutate, Constants.CLIENT_IP, IpUtils.getClientIp(request));

                return chain.filter(exchange.mutate().request(mutate.build()).build());
            });
        });
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value)
    {
        if (value == null)
        {
            return;
        }
        String valueStr = value.toString();
//        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueStr);
    }

    //异常请求头里的指定header
    private void removeHeader(ServerHttpRequest.Builder mutate, String name)
    {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, 401);
    }

    /**
     * 获取缓存key
     */
    private String getTokenKey(String token)
    {
        return Constants.ACCESS_TOKEN.concat(token);
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst(Constants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (!StringUtil.isNullOrEmpty(token) && token.startsWith(Constants.PREFIX))
        {
            token = token.replaceFirst(Constants.PREFIX, "");
        }
        return token;
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
